package com.hiyee.utils;

import com.hiyee.enums.BnFormatEnum;
import com.hiyee.response.ResponseStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 系统实体编号生成工具类
 *
 * @author WangBin
 */
@Component
public class BnBuilderUtil {

    public final static String REDIS_KEY_BN = "build_bn_";
    @Autowired
    private RedisOperator redisOperator;

    public String build(BnFormatEnum bnFormatEnum) {
        String format = bnFormatEnum.getFormat();
        if(format == null)return "";
        // 截取最后一个字符，表示补零的位数
        int padding = Integer.parseInt(format.substring(format.length() - 1));
        format = format.substring(0, format.length() - 1);
        // 取 redis 自增值
        String redisKey = REDIS_KEY_BN + bnFormatEnum.getKey();
        String incrementVal = redisOperator.get(redisKey);
        if(incrementVal == null) {
            incrementVal = "1";
            // 增加 redis 自增键
            redisOperator.set(redisKey, "1", DateTimeUtil.getRemainSecondsOneDay(new Date()));
        }
        return String.format(format, DateTimeUtil.getDateTimeStr("yyyyMMdd")) + String.format("%0" + padding + "d", Integer.parseInt(incrementVal));
    }
}
